package ling.archives.common;

import lombok.var;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;

public class FieldInit {
        public  void PowerStrSet(Object obj, BiFunction<Field,Object,String> func) {
            if (obj == null)
                return ;
            if(func==null)
                func= this::fmtValByName  ;
            var classz=obj.getClass();
            Field[] fields = classz.getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || !Modifier.isPublic(field.getModifiers()))
                    continue;
                try {
                    if (field.getType() == String.class)
                        field.set(obj, func.apply(field, obj));
                    else if (field.getType().getClassLoader() == null)
                        PowerStrSet(field.get(obj),func);
                } catch (IllegalAccessException e) {
                    System.out.println("属性设置异常");
                    e.printStackTrace(System.out);
                }
            }
        }
        public List<String> gainList(Object obj,List<String> list) {
            if (obj == null)
                return list;
            if (list == null)
                list = new ArrayList<>();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!Modifier.isPublic(field.getModifiers()))
                    continue;
                try {
                    if (field.getType() == String.class || field.getType().isPrimitive()) {
                        list.add(field.get(obj) + "");
                    } else if (field.getType().getClassLoader() == null)
                        gainList(field.get(obj), list);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
            return list;
        }
        public String fmtValByName(Field field, Object obj){
            var classz=field.getGenericType();
            return classz.getClass().getSimpleName()+":"+field.getName();
        }


}
